package com.example.mylogin.config;

import cn.hutool.core.net.NetUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.example.mylogin.constant.CommonConstant;
import com.example.mylogin.interceptor.SqlInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 * 功能描述：mybatis配置，插件装配 -> 就是通过插件对mybatis进行拦截增强，常见的插件如下 ->
 * 1. 自动分页: PaginationInnerInterceptor
 * 2. 多租户: TenantLineInnerInterceptor
 * 3. 动态表名: DynamicTableNameInnerInterceptor
 * 4. 乐观锁: OptimisticLockerInnerInterceptor
 * 5. 性能规范: IllegalSQLInnerInterceptor
 * 6. 防止全表更新与删除: BlockAttackInnerInterceptor
 * </p>
 *
 * @author cui haida
 * @date 2024/04/30/13:59
 */
@Configuration
public class MybatisConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 新建一个mybatis plus中断器对象
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor());

        // 乐观锁插件
        mybatisPlusInterceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());

        return mybatisPlusInterceptor;
    }

    // 将日志打印的拦截器加入mybatis配置中
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return configuration -> configuration.addInterceptor(new SqlInterceptor());
    }

    /**
     * 分页插件
     * @return 分页中断器
     */
    private InnerInterceptor paginationInnerInterceptor() {
        // 新建一个MySQL分页对象
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        paginationInnerInterceptor.setOverflow(true);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制，这里设置800
        paginationInnerInterceptor.setMaxLimit(CommonConstant.MAX_PAGE_COUNT);

        return paginationInnerInterceptor;
    }

    /**
     * 乐观锁插件
     * @return 乐观锁中断器
     */
    public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

    /**
     * 使用网卡信息绑定雪花生成器，防止集群雪花ID重复
     * @return 雪花生成器
     */
    @Bean
    public IdentifierGenerator idGenerator() {
        return new DefaultIdentifierGenerator(NetUtil.getLocalhost());
    }
}
